package com.xxx.filter;

import com.xxx.pojo.User;
import com.xxx.util.JWTUtil;
import com.xxx.util.ThreadLocalUntil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String uri = req.getRequestURI();

        String[] uris ={"/login","js","css","images","/getCode","html","load"};
        for (String s : uris) {
            if(uri.contains(s)){
                chain.doFilter(request, response);
                return;
            }
        }

        String token = req.getHeader("token");
        if (token == null){
//            resp.sendRedirect("http://localhost:8080/font/page/login.html");
            resp.setStatus(401);
            return;
        }
        String id = JWTUtil.verifyToken(token);

        if (id == null){
//            resp.sendRedirect("http://localhost:8080/font/page/login.html");
            resp.setStatus(401);
        }else {
            ValueOperations<String, Object> ops = redisTemplate.opsForValue();
            User user = (User) ops.get(id);
            ThreadLocalUntil.setCurrentId(user.getId());
            chain.doFilter(request, response);
        }

    }
}
